import type { $Fetch } from "ofetch";
import { useRuntimeConfig } from "#app";
import { ofetch } from "ofetch";
import { userSet } from "./user";
import { ref } from "vue";

let http: $Fetch;
export const globalLoading = ref(false);

export function setupHttp() {
  if (http) return http;

  const config = useRuntimeConfig();
  const baseURL = config.public.apiBase as string;

  http = ofetch.create({
    baseURL,
    headers: { "Content-Type": "application/json" },
    async onRequest({ options }) {
      globalLoading.value = true;
      const { getToken } = userSet();
      const token = getToken();
      if (token) {
        options.headers = {
          ...options.headers,
          Authorization: `Bearer ${token}`,
        } as any;
      }
    },
    async onResponse() {
      globalLoading.value = false;
    },
    async onResponseError({ request, response, options }) {
      globalLoading.value = false;
      const { message } = response._data;
      if (Array.isArray(message)) {
        message.forEach((item) => {
          httpStatusErrorHandler?.(item, response.status);
        });
      } else {
        httpStatusErrorHandler?.(message, response.status);
      }

      if (response.status === 401) {
        const { clearUserData } = userSet();
        clearUserData();
      }
      return Promise.reject(response._data);
    },
    retry: 3,
    retryDelay: 1000,
  });

  return http;
}
type HttpStatusErrorHandler = (message: string, statusCode: number) => void;
let httpStatusErrorHandler: HttpStatusErrorHandler;
export function injectHttpStatusErrorHandler(handler: HttpStatusErrorHandler) {
  httpStatusErrorHandler = handler;
}
export function getHttp() {
  if (!http) {
    throw new Error("HTTP client not initialized. Call setupHttp first.");
  }
  return http;
}
